import {
  generateCrudPage,
  headerToolbar,
  bulkActions,
  listButtons,
} from "./sys_columns.ts";
import { parse } from 'url';
import adminCrud from "./sys_admin_crud.ts";
import { db } from "../../../config/db/connectiondb.ts";
import { successResponse, errorResponse } from "../../helpers.ts";
const apiUrl = "/admin-api/system/admin_menus";
import AdminMenus from "../models/AdminMenus.ts";
export async function grid() {
  const list = {
    apiUrl: apiUrl,
    headerToolbar: await headerToolbar(apiUrl, form), //头部工具栏
    bulkActions: await bulkActions(), //批量操作
    filter: await filter(), //筛选
    showIndex: false, //是否显示序号列
    draggable: true, //是否可拖拽排序

    columns: [
      { name: "id", label: "ID" },
      { name: "title", label: "名称", searchable: true },
      { name: "icon", label: "图标" },
      {
        type: "mapping",
        name: "url_type",
        label: "类型",
        map: {
          1: "<span class='label label-info'>路由</span>",
          2: "<span class='label label-success'>外链</span>",
          3: "<span class='label label-danger'>Iframe</span>",
          4: "<span class='label label-warning'>页面</span>",
        },
      },
      { name: "url", label: "链接" },
      {
        name: "custom_order",
        label: "排序",
        quickEdit: {
          type: "input-number",
          min: 0,
          saveImmediately: true,
        },
      },
      {
        name: "visible",
        label: "可见",
        quickEdit: {
          type: "checkbox",
          mode: "inline",
          saveImmediately: true,
        },
      },
      {
        name: "is_home",
        label: "首页",
        quickEdit: {
          type: "checkbox",
          mode: "inline",
          saveImmediately: true,
        },
      },

      await listButtons({
        types: ["edit", "detail", "delete"],
        apiUrl: apiUrl,
        detail: detail,
        form: form,
      }),
    ],
  };
  return await generateCrudPage(list);
}

//表单配置
async function form() {
  return [
    { type: "input-text", name: "title", label: "名称", required: true },
    { type: "input-text", name: "icon", label: "图标" },
    {
      type: "select",
      name: "parent_id",
      label: "父级",
      searchable: true,
      selectMode: "tree",
      options: await getMenuTreeOptions(),
    },
    {
      type: "input-number",
      name: "custom_order",
      label: "排序",
      min: 0,
      value: 0,
    },
    {
      type: "switch",
      name: "visible",
      label: "可见",
      onText: "是",
      offText: "否",
    },
    {
      type: "list-select",
      name: "url_type",
      label: "类型",
      options: [
        { label: "路由", value: 1 },
        { label: "外链", value: 2 },
        { label: "Iframe", value: 3 },
        { label: "页面", value: 4 },
      ],
      value: 1,
    },
    {
      type: "input-text",
      name: "url",
      label: "链接地址",
      required: true,
      validateOnChange: true,
      validations: {
        matchRegexp: "^(https?:\\/\\/)",
      },
      validationErrors: {
        matchRegexp: "需要以 http(s):// 开头",
      },
      placeholder: "例如：https://www.baidu.com",
      visibleOn: "url_type == 2",
    },
    {
      type: "input-text",
      name: "url",
      label: "路由路径",
      required: true,
      validateOnChange: true,
      validations: {
        matchRegexp: "^/",
      },
      validationErrors: {
        matchRegexp: "需要以 / 开头",
      },
      placeholder: "例如：/admin_menus",
      visibleOn: "url_type == 1",
    },
    {
      type: "textarea",
      name: "component",
      label: "页面组件",
      required: true,
      minRows: 5,
      placeholder: "请输入html内容",
      visibleOn: "url_type == 4",
    },
    {
      type: "input-text",
      name: "url",
      label: "Iframe 链接",
      required: true,
      validateOnChange: true,
      placeholder: "例如：https://www.example.com",
      visibleOn: "url_type == 3",
    },
  ];
}

//详情配置
async function detail() {
  return {
    title: "查看详情",
    body: {
      type: "form",
      body: [
        {
          type: "input-text",
          name: "title",
          label: "名称",
          value: "${title}",
          disabled: true,
        },
        {
          type: "mapping",
          name: "url_type",
          label: "类型",
          map: {
            1: "路由",
            2: "外链",
            3: "Iframe",
            4: "页面",
          },
          value: "${url_type}",
        },
      ],
    },
  };
}

//筛选配置
async function filter() {
  return {
    title: "筛选",
    mode: "inline",
    controls: [
      { type: "input-text", name: "title", label: "名称" },
      { type: "submit", label: "查询", level: "primary" },
      { type: "reset", label: "重置" },
    ],
  };
}

export const SysMenusController = {
  async index(req, res) {
    const query = parse(req.url, true).query;
    if (query._replace === "1") {
      const list = await grid();
      return successResponse(res, {data: list});
    }
    try {
      const query = AdminMenus.query();
      if (req.query.title) {
        query.where("title", "like", `%${req.query.title}%`);
      }
      const list = await query.orderBy("custom_order", "ASC").paginate(req.query.page, req.query.perPage);
      return successResponse(res, {data: list.items()});
    } catch (error) {
      console.error("获取菜单列表失败:", error);
      return errorResponse(res, {msg: "服务器错误，请稍后重试"});
    }
  },

  async store(req, res) {
   const query = parse(req.url, true).query;
    if (query._action === "saveOrder") {
      return saveOrder(req, res, db);
    }
    if (query._action === "quickEditItem") {
      try {
        const result = AdminMenus.query()
          .where("id", req.body.id)
          .update({
            visible: req.body.visible,
            is_home: req.body.is_home,
            custom_order: req.body.custom_order,
          });
        return successResponse(res, {msg: result ? "保存成功！" : "保存失败！"});
      } catch (error) {
        console.error("数据库错误：", error);
        return apiResponse(res, 500, 1, "服务器错误！");
      }

      //return adminCrud.update(req, res, AdminMenus);
    }
    // 如果是新增菜单，走默认 store
    // 如果是保存排序，
    // 其他情况走默认 store
    //return adminCrud.store(req, res, AdminMenus);
  },

  async edit(req, res) {
    return adminCrud.edit(req, res, AdminMenus);
  },

  async update(req, res) {
    return adminCrud.update(req, res, AdminMenus);
  },
  async destroy(req, res) {
    return adminCrud.destroy(req, res, AdminMenus);
  },
};

// 排序保存方法
async function saveOrder(req, res, db) {
  let { ids } = req.body;
  if (!ids || typeof ids !== "string") {
    return errorResponse(res, {msg: "排序数据无效！"});
  }
  try {
    // 1. 解析 ids 字符串成顺序 id 数组
    const idList = [];
    const regex = /\d+/g;
    let match;
    while ((match = regex.exec(ids)) !== null) {
      idList.push(parseInt(match[0], 10));
    }

    if (idList.length === 0) {
      return errorResponse(res, {msg: "没有可排序的菜单！"});
    }

    // 2. 拼接 case when 语句
    let caseSql = "";
    idList.forEach((id, index) => {
      caseSql += `when ${id} then ${index * 10} `;
    });

    // 3. 执行批量保存
    await AdminMenus.query()
      .whereIn("id", idList)
      .update({
        custom_order: db.raw(`
          case id
            ${caseSql}
            else custom_order
          end
        `),
      });

    return successResponse(res, {msg: "保存成功！"});
  } catch (error) {
    console.error("保存排序出错：", error);
    return errorResponse(res, {msg: "服务器错误！"});
  }
}

export async function getMenuTreeOptions(parentId = 0) {
  const menus = await AdminMenus.query()
    .select("id", "title", "parent_id", "custom_order")
    .orderBy("custom_order", "asc")
    .get();

  const buildTree = (data, pid) => {
    return data
      .filter((menu) => menu.parent_id === pid)
      .map((menu) => {
        const children = buildTree(data, menu.id);
        const option = {
          label: menu.title,
          value: menu.id,
        };
        if (children.length > 0) {
          option.children = children;
        }
        return option;
      });
  };

  return buildTree(menus.toData(), parentId);
}
